<template>
  <div>
    <el-tree ref="treeRef" node-key="id" :data="permissionList" :props="{label:'name'}" show-checkbox default-expand-all check-strictly />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionList: [] // 保存权限列表
    }
  },
  created() {
    this.loadPermissionList()
    this.loadRoleDetail()
  },
  methods: {
    // 获取权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('获取权限列表成功', res)
        // 保存数据
        this.permissionList = tranListToTreeData(res.data)
      } catch (err) {
        console.log('获取权限列表失败', err)
      }
    },
    // 根据id获取当前角色拥有的权限 -> 回填
    async loadRoleDetail() {
      try {
        const res = await getRoleDetail(this.curId)
        console.log('根据id获取当前角色拥有的权限成功', res)
        // 数据回填
        this.$refs.treeRef.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log('根据id获取当前角色拥有的权限失败', err)
      }
    },
    // 给角色分配权限
    async doSave() {
      try {
        const permIds = this.$refs.treeRef.setCheckedKeys()
        const res = await assignPerm({ id: this.curId, permIds })
        console.log('给角色分配权限成功', res)
        this.$message.success('修改权限成功')
        // 请求成功关闭弹窗
        this.$emit('success')
      } catch (err) {
        console.log('给角色分配权限失败', err)
      }
    },
    // 确定
    hSubmit() {
      this.doSave()
    },
    // 取消
    hClose() {
      this.$emit(close)
    }
  }
}
</script>

<style>

</style>
